<?php

namespace app\admin\controller;

use app\common\model\Res;
use think\Db;

//送货任务书
class Company extends Base
{

    private $tableName = 'sys_company';

    private function getWhere()
    {
        return function ($query) {
            $input_status = input('input_status');
            if ($input_status != null) {
                $query->where('company.input_status', $input_status);
            }
            $inUser = input('inUser');
            if ($inUser) {
                $query->where('company.create_user_id', $this->user_id);
            }
            $inCompany = input('inCompany');
            if ($inCompany) {
                $companyIds = Db::table('sys_user')
                                ->where('id', $this->user_id)
                                ->value('company_ids');
                if ($companyIds !== '*') {
                    $query->where('company.id', 'in', $companyIds);
                }
            }
            //
            $name = input("name");
            if ($name) {
                $query->where('company.name', 'like', '%' . $name . '%');
            }
        };
    }

    /*
    * 获取列表
    *
    */
    public function getList($currentPage = 1, $pageSize = 10, $noPage = 0)
    {
        $res = new Res();
        try {
            $where = $this->getWhere();
            $order = [];
            $sortProp = input('get.sortProp');
            if ($sortProp) {
                $order[$sortProp] = input('get.sortOrder') == 'ascending' ? '' : 'desc';
            } else {
                $order['company.create_time'] = 'desc';
            }
            $fields = [
                'company.*'
            ];
            $sql = Db::table($this->tableName)
                     ->alias('company')
                     ->field($fields)
                     ->where($where)
                     ->order($order);
            if ($noPage) {
                $list = $sql->select();
                $total = count($list);
            } else {
                $list = $sql->page($currentPage, $pageSize)
                            ->select();
                $total = Db::table($this->tableName)
                           ->alias('company')
                           ->where($where)
                           ->count();
            }
            $data['list'] = $list;
            $data['total'] = $total;
            $res->data = $data;
            $res->code = 0;
        } catch (\Exception $e) {
            $res->success = false;
            $res->message = $e->getMessage();
        }
        return json($res);
    }

    /**
     * 创建或更新
     *
     * @param
     */
    public function save()
    {
        $res = new Res();
        Db::startTrans();
        try {
            $data = [];
            $fields = [
                'name',
                'address',
                'is_disabled',
                'update_time',
                'update_user_id'
            ];
            $now = date('Y-m-d H:i:s');
            $post = input('post.');
            $post['update_time'] = $now;
            $post['update_user_id'] = $this->user_id;
            if (!$post['id']) {
                $fields[] = 'create_time';
                $fields[] = 'create_user_id';
                $fields[] = 'create_user_name';
                $post['create_time'] = $now;
                $post['create_user_id'] = $this->userId;
                $post['create_user_name'] = Db::table('sys_user')
                                              ->where('id', $this->user_id)
                                              ->value('name');
                $post['id'] = Db::table($this->tableName)
                                ->field($fields)
                                ->insertGetId($post);
            } else {
                $data = Db::table($this->tableName)
                          ->find($post['id']);
                if (!$data) {
                    throw new \Exception('找不到该公司信息！');
                }
                Db::table($this->tableName)
                  ->field($fields)
                  ->update($post);
            }
            $data = array_merge($data, $post);
            $res->data = [
                'id' => $data['id']
            ];
            $res->code = 0;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $res->message = $e->getMessage();
        }
        return json($res);
    }

    /*
    * 删除
    */
    public function del($id)
    {
        $res = new Res();
        Db::startTrans();
        try {
            $company = Db::table($this->tableName)
                         ->find($id);
            if (!$company) {
                throw new \Exception('找不到该公司信息！');
            }
            Db::table($this->tableName)
              ->delete($id);
            $res->code = 0;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $res->success = false;
            $res->message = $e->getMessage();
        }
        return json($res);
    }

    /**
     * 检查名称唯一性
     *
     * @param
     */
    public function checkNameUnique($name, $id = null)
    {
        $res = new Res();
        try {
            $where = [
                'name' => $name
            ];
            if ($id) {
                $where['id'] = [
                    '<>',
                    $id
                ];
            }
            $res->data = Db::table($this->tableName)
                           ->where($where)
                           ->count();
            $res->code = 0;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $res->message = $e->getMessage();
        }
        return json($res);
    }
}